package com.wpzf.ndhc.controller;

import com.alibaba.fastjson.JSON;
import com.wpzf.common.core.utils.ServletUtils;
import com.wpzf.common.core.utils.StringUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.common.security.service.TokenService;
import com.wpzf.common.security.utils.SecurityUtils;
import com.wpzf.ndhc.domain.*;
import com.wpzf.ndhc.service.WpzfNdhcTbBaseService;
import com.wpzf.ndhc.service.WpzfNdhcTbhcjgService;
import com.wpzf.ndhc.utils.WpzfNdhcGdalUtils;
import com.wpzf.system.api.model.LoginUser;
import com.wpzf.zxhc.utils.MultipleFileUnZip;
import net.lingala.zip4j.exception.ZipException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wpzfndhctbbase")
public class WpzfNdhcTbBaseInfoController {

    @Autowired
    TokenService tokenService;

    @Autowired
    WpzfNdhcTbBaseService wpzfNdhcTbBaseServiceImpl;

    @Value("${tempath}")
    public String tempath;

    @Autowired
    WpzfNdhcTbhcjgService wpzfNdhcTbhcjgService;


    @RequestMapping(value = "/queryUserByHctbId", method = RequestMethod.POST)
    public AjaxResult queryUserByHctbId(@RequestBody Map<String, Object> parm) {
        try {
            String operName = SecurityUtils.getUsername();
            parm.put("username", operName);


            WpCjTbBaseinfoDTO wpcjTbBaseinfoDTO = new WpCjTbBaseinfoDTO();
            //获取地块信息  dkxxbxjDTOS
            WpCjDkxxbDTO wpcjDkxxbDTO = wpzfNdhcTbBaseServiceImpl.querydkxxBytbbh(parm);
            wpcjTbBaseinfoDTO.setWpCjDkxxbDTO(wpcjDkxxbDTO);


            //获取图斑信息 相关图斑全部查出
            List<WpCjTbxxbDTO> wpCjTbxxbDTOS = wpzfNdhcTbBaseServiceImpl.querytbxxBytbbh(parm);
            wpcjTbBaseinfoDTO.setWpCjTbxxbDTOS(wpCjTbxxbDTOS);


            //其他相关的拆分图斑
            List<WpCjDkxxbDTO> wpCjDkxxbrelatedto = wpzfNdhcTbBaseServiceImpl.querydkxxrelateBytbbh(parm);
            wpcjTbBaseinfoDTO.setWpCjDkxxbrelatedto(wpCjDkxxbrelatedto);

            //获取图斑核查结果 0,1,2,3 单位  监理  监理结果确认  整改  按照pid获取
            //parm.put("pid", wpcjDkxxbDTO.getId());
            List<WpCjTbhcjgDTO> wpCjTbhcjgDTOS = wpzfNdhcTbhcjgService.querytbhcjgBytbbh(parm);
            wpcjTbBaseinfoDTO.setWpCjTbhcjgDTOS(wpCjTbhcjgDTOS);

            String xzqdm = "";
            if (wpcjDkxxbDTO != null) {
                String bghXzqdm = wpcjDkxxbDTO.getBghxzqdm();
                if (!"".equals(bghXzqdm) && !"null".equals(bghXzqdm) && bghXzqdm != null) {
                    xzqdm = bghXzqdm.replace("\r", "");
                    ;
                    parm.replace("xzqdm", xzqdm);
                }
            }
            //举证照片
            ModelMap modelMap = wpzfNdhcTbBaseServiceImpl.getShowImgs(parm);
           wpcjTbBaseinfoDTO.setModelMap(modelMap);

            //图斑截图
//            List<WpCjTbjtNdDTO> wpCjTbjtDTOS = wpzfNdhcTbBaseServiceImpl.querytbjtBytbbh(parm);
            List<WpCjTbjtNdDTO> wpCjTbjtDTOS = wpzfNdhcTbBaseServiceImpl.getTbjtByHyjgurl(wpCjTbxxbDTOS.get(0).hyjgurl);
            wpcjTbBaseinfoDTO.setWpCjTbjtDTOS(wpCjTbjtDTOS);


            return AjaxResult.success("获取成功", wpcjTbBaseinfoDTO);
        } catch (Exception ex) {
            return AjaxResult.error("获取失败", ex.toString());
        }
    }


    //查询图斑批次号
    @RequestMapping(value = "/getPch", method = RequestMethod.POST)
    public AjaxResult getPch(@RequestBody Map<String, Object> param) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String,Object>> rest = wpzfNdhcTbBaseServiceImpl.getPch(param);
        return AjaxResult.success("查询图斑批次号", rest);
    }


    //查询市
    @RequestMapping(value = "/getShi", method = RequestMethod.POST)
    public AjaxResult getShi(@RequestBody Map<String, Object> param) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String,Object>> rest = wpzfNdhcTbBaseServiceImpl.getShi(param);
        return AjaxResult.success("查询市", rest);
    }

    //查询县
    @RequestMapping(value = "/getXian", method = RequestMethod.POST)
    public AjaxResult getXian(@RequestBody Map<String, Object> param) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String,Object>> rest = wpzfNdhcTbBaseServiceImpl.getXian(param);
        return AjaxResult.success("查询县", rest);
    }

    //根据用户省市权限查询图斑信息列表
    @RequestMapping(value = "/queryTbList", method = RequestMethod.POST)
    public AjaxResult queryTbList(@RequestBody Map<String, Object> param) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String,Object>> rest = wpzfNdhcTbBaseServiceImpl.queryTbList(param);
        Integer cnt = wpzfNdhcTbBaseServiceImpl.queryTbListCount(param);
        return AjaxResult.success("查询图斑信息列表", rest,cnt);
    }

    //根据用户省市权限查询图斑信息列表  根据index查询
    @RequestMapping(value = "/queryTbByIndex", method = RequestMethod.POST)
    public AjaxResult queryTbByIndex(@RequestBody Map<String, Object> param) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
        Map<String,Object> rest = wpzfNdhcTbBaseServiceImpl.queryTbByIndex(param);
        return AjaxResult.success("查询图斑", rest);
    }

    //查询图斑详情信息
    @RequestMapping(value = "/queryTbDetails", method = RequestMethod.POST)
    public AjaxResult queryTbDetails(@RequestBody Map<String, Object> param) {
        Map<String,Object> rest = new HashMap<>();

        param.put("dkbh",param.get("jcbh"));

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());

        //图斑信息
        Map<String,Object> tbInfo = wpzfNdhcTbBaseServiceImpl.queryTbInfoByTbbsm(param);
        //地块信息
        List<Map<String,Object>> dkInfo = wpzfNdhcTbBaseServiceImpl.queryDkInfoByTbbsm(param);

        //举证照片
//        ModelMap modelMap = getShowImgs(param);
        List<WpSjHcfjNdDTO> wpSjHcfjNdDTOList = new ArrayList<>();
        if (dkInfo!=null&&dkInfo.size()>0) {
            wpSjHcfjNdDTOList = wpzfNdhcTbBaseServiceImpl.querySjHcfjByDkbsm(dkInfo);
            rest.put("hcfj", wpSjHcfjNdDTOList);
        } else {
            rest.put("hcfj", wpSjHcfjNdDTOList);
        }

        rest.put("tbInfo",tbInfo);
        rest.put("dkInfo",dkInfo);


        return AjaxResult.success("查询图斑详情信息", rest);
    }

    public static ModelMap getShowImgs(Map<String, Object> parm) {
        ModelMap map = new ModelMap();
        try {
            String dkbh = parm.get("dkbh") + "";
            String xzqdm = parm.get("xzqdm") + "";
            String postURL = "";
            String data = "";
            {
                postURL = "https://jg.landcloud.org.cn:8553/webapi/token";
                data = "client_id=web&client_secret=e46232c20609435eba54b7576de935dd&grant_type=password&username=a53e0c14ee900728f36bba014d975982&password=b30c775c48e9ba92ade95e427a5242b0";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            //关闭流
            is.close();

            conn.disconnect();
            String result = new String(datas, 0, datas.length, "utf-8");
            List<String> items = new ArrayList<>();
            {
//                String t = getImg(result, "00gty_wpzf_nddk", xzqdm, dkbh);
                String t = getImgNew(result, "00gty_wpzf_nddk", xzqdm, dkbh);
                items.add(t);
                map.put("data", items);
            }
        } catch (Exception e) {
            System.err.println(e);
            return map;
        }
        return map;
    }

    public static String getImgNew(String str, String ywmb, String xzqdm, String dkbh) {
        String rest = "";
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            Map mapType = JSON.parseObject(str, Map.class);
            {
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://dc2.landcloud.org.cn:9443/webapi/getprojectCG/ndbg2024";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            String encoding = com.wpzf.common.core.utils.sign.Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            //  out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            //String xmbh="210115S120240216LJ00005";
            if (StringUtils.isNotBlank(xzqdm)) {
                String data = "{\"xzqdm\":\"" + xzqdm + "\",\"xmbh\":[\"" + dkbh + "\"]}";
                System.out.println("---------获取地块列表参数------" + data);
                out.write(data);
                out.flush();
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
            }

        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            //writeLog(UtilTool.GetTime_1()+"："+e.getMessage()+"\n");
            throw new RuntimeException(e.getMessage());
        }
        return rest;
    }


    //导出图斑列表
    @RequestMapping(value = "/exportTbList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public AjaxResult exportTbList(@RequestBody Map<String, Object> param, HttpServletResponse response) {
        String rest = "";
        String msg = "";
        com.wpzf.ndhc.utils.WpzfNdhcExcelUtils excel = new com.wpzf.ndhc.utils.WpzfNdhcExcelUtils();
        List<String> Colomnlist = new ArrayList<>();
        Colomnlist.clear();
        Colomnlist.add("序号");
        Colomnlist.add("图斑标识码");
        Colomnlist.add("县级行政区代码");
        Colomnlist.add("县级行政区名称");
        Colomnlist.add("乡镇代码");
        Colomnlist.add("乡镇名称");
        Colomnlist.add("监测图斑编号");
        Colomnlist.add("监测图斑类型");
        Colomnlist.add("图斑特征");
        Colomnlist.add("影像采集时间");
        Colomnlist.add("监测面积");
        Colomnlist.add("监测椭球面积");
        Colomnlist.add("农用地面积");
        Colomnlist.add("耕地面积");
        Colomnlist.add("其他农用地面积");
        Colomnlist.add("建设用地面积");
        Colomnlist.add("未利用地面积");
        Colomnlist.add("农转用建设用地项");
        Colomnlist.add("增减挂钩项目建新");
        Colomnlist.add("先行用地项目");
        Colomnlist.add("未利用地开发项");
        Colomnlist.add("增减挂钩项目拆旧");
        Colomnlist.add("土地整治验收项");
        Colomnlist.add("工矿废弃地复垦项");
        Colomnlist.add("设施农用地项");
        Colomnlist.add("临时用地项");
        Colomnlist.add("矿权信息");
        Colomnlist.add("占基本农田面积");
        Colomnlist.add("占生态保护红线面积");
        Colomnlist.add("自然保护地名称");

        String operName = SecurityUtils.getUsername();
        param.put("username", operName);
        //获取图斑列表
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String,Object>> list = wpzfNdhcTbBaseServiceImpl.queryTbList(param);
        rest = excel.exportTbList(response, "图斑列表", list, Colomnlist, tempath);
        if (rest.contains("error")) {
            msg = "导出失败";
        } else {
            msg = "导出成功";
        }
        return AjaxResult.success(msg, rest);
    }

    //导出矢量
    @RequestMapping(value = "/exportShpList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public AjaxResult exportShpList(@RequestBody Map<String, Object> param, HttpServletResponse response) throws ZipException {
        String rest = "";
        String msg = "";

        WpzfNdhcGdalUtils gdalutil = new WpzfNdhcGdalUtils();
        String operName = SecurityUtils.getUsername();
        param.put("username", operName);
        //获取图斑列表
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String,Object>> list = wpzfNdhcTbBaseServiceImpl.queryTbList(param);
        rest = gdalutil.exportTbList(response, list, tempath);
        if (rest.contains("error")) {
            msg = "导出失败";
        } else {
            List<String> arr = new ArrayList<>();
            arr.add(tempath + "\\" + rest);  //shp
            String zippath = tempath + "\\" + rest.replace("shp", "zip");
            //生成了shp
            String str = tempath + "\\" + rest.replace("shp", "prj");
            File file = new File(str);
            if (file.exists()) {
                arr.add(str);  //prj
            }

            str = tempath + "\\" + rest.replace("shp", "dbf");
            file = new File(str);
            if (file.exists()) {
                arr.add(str);  //prj
            }
            str = tempath + "\\" + rest.replace("shp", "shx");
            file = new File(str);
            if (file.exists()) {
                arr.add(str);  //prj
            }
            MultipleFileUnZip multipleFileUnZip = new MultipleFileUnZip();
            rest = multipleFileUnZip.fileZip(zippath, arr);
            if (rest == "") {
                File file1 = new File(zippath);
                rest = file1.getName();
                msg = "导出成功";
            } else {
                msg = "导出失败";
            }
        }
        return AjaxResult.success(msg, rest);
    }








    //地块详情信息
    @RequestMapping(value = "/queryDkDetails", method = RequestMethod.POST)
    public AjaxResult queryDkDetails(@RequestBody Map<String, Object> param) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.put("user_name", loginUser.getSysUser().getUserName());
        Map<String, Object> rest = wpzfNdhcTbBaseServiceImpl.queryDkDetails(param);
        return AjaxResult.success("地块详情信息", rest);
    }

}




